/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var currentLoad;

function loadReplies(streamId, threadId, index, length, show) {
    var pl = new SOAPClientParameters();
    pl.add('threadId', threadId);
    pl.add('streamId', Base64.encode(streamId));
    dateFrom = $('#from').val();
    dateTo = $('#to').val();
    pl.add('dateFrom', dateFrom);
    pl.add('dateTo', dateTo);
    pl.add('index', index);
    pl.add('length', length);
    SOAPClient.invoke('/m', 'getReplies', pl, true, getRepliesComplete);
}
var json;
function getRepliesComplete(r) {
    if (r.trim() != 'Your query has no result! Try again!') {
        currentLoad.removeClass('hide');
        currentLoad.next().addClass('hide');
        //console.log(r.trim());
        var result = JSON.parse(r.trim());
        var items = result.items;
        //console.log(items);
        var keyword = doSearchInStream.value;
        var searchHide = '';
        var highlighReadMore = '';
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            var id = item.id;
            var threadId = item.threadId;
            var author = item.author;
            var likes = item.likes;
            var sentiment = item.sentiment;
            var text = item.text;
            if (keyword != '') {
                var re = new RegExp('(' + keyword + ')(?=[^>]*(<|$))', "gi");
                if (text.search(re) !== -1) {
                    text = text.replace(re, '<span class="highlight">$1</span>');
                    if (hideText) {
                        highlighReadMore = 'highlight';
                    }
                }
                else {
                    searchHide = 'display: none';
                }
            }
            var time = toDateTime(new Date(item.time));
            var from100 = text;
            var showText = text;
            var hideText = '';
            if (text === null) continue;
            if (text.length > 100) {
                from100 = text.substr(100);
                showText = text.substr(0, from100.indexOf(' ') + 100);
                hideText = text.substr(from100.indexOf(' ') + 101);
                if (keyword != '') {
                    var re = new RegExp('(' + keyword + ')', "gi");
                    if (text.search(re) !== -1) {
                        highlighReadMore = 'highlight';
                    }
                    else {
                        searchHide = 'display: none';
                    }
                }
            }
            var html = '<div class="user-author-mention-actions mention-top-bar hide" style="height: auto; ' + searchHide + '">\
                            <div class="float-left user-image">\
                                        <img style="width: 32px; height: 32px; border-radius: 0;" src="Images/avatar.png">\
                                            </div>\
                            <div class="float-left main-reply-content">\
                                <p style="overflow: hidden; display: block;"><strong>' + author + ': </strong><span>' + showText + '</span>';
            if (hideText != '') {
                html += '<span class="readmore-threedot">...</span>\
                        <span class="readmore spanshow ' + highlighReadMore + '" onclick="expand(this);" style="color: orange; cursor: pointer; white-space: nowrap;">Read more</span>\
                        <span class="readmore-content hide">' + hideText + '</span>\
                        <span class="readmore spanshow hide" onclick="unexpand(this);" style="color: orange; cursor: pointer; white-space: nowrap;">Show less</span>';
            }
            html += '</p>\
                            </div>\
                            <div class="float-right">\
                                <span class="task-posted-time" style="line-height: 22px">' + time + '</span>\
                            </div>\
                            <div class="thread-details">\
                                <div class="numberOfLikes">\
                                    <i class="icon-mention-likes"></i>\
                                    <div>' + likes + '</div>\
                                </div>\
                            </div>\
                            <div class="mention-right-action-bar" style="top: inherit;">\
                                <ul class="nav nav-list right-action-bar" date="' + time + '" messageid="' + id + '" threadid="' + threadId + '">\
                                    <li class="right-action-item sentiment-item-list">\
                                        <div class="sentiment">\
                                            <a class="set-filter ' + sentiment.text + ' cursor-pointer" rel="tooltip" title="Show all ' + sentiment.text + ' mentions" style="background-color: ' + sentiment.color + ';">\
                                                <i class="icon-' + sentiment.text + '" style="background-color: ' + sentiment.color + ';"></i><span class="text-to-hide">' + sentiment.text + '</span>\
                                            </a>\
                                        </div>\
                                        <div class="btn-group">\
                                            <button class="btn btn-small dropdown-toggle" style="width: 25px;"><i class="icon-right-dropdown"></i></button>\
                                        </div>\
                                    </li>\
                                </ul>\
                            </div>\
                        </div>';
            currentLoad.parent().before(html);
        }
        $('.mention-text:not(.url-parsed), .main-reply-content:not(.url-parsed)').each(function() {
            $(this).html(parseURL($(this).html()));
            $(this).addClass('url-parsed');
        });
    }
    else {
        currentLoad.parent().remove();
        showMessage('No more reply to show... Please come back later!')
    }
}

$(document).on('click', '.loadMoreReply a', function() {
    currentLoad = $(this);
    $(this).addClass('hide');
    $(this).next().removeClass('hide');
    var shareBtn = $(this).parents('li').find('.retweet_dropdown');
    var streamId = shareBtn.attr('streamid');
    var threadId = shareBtn.attr('threadid');
    var index = $(this).parent().parent()[0].children.length - 1;
    var length = 5;
    if (currentLoad.parent().parent().children('.hide').length > 0) {
        currentLoad.parent().parent().children('.hide').removeClass('hide');
        loadReplies(streamId, threadId, index, length, false);
    }
    else {
        loadReplies(streamId, threadId, index, length, true);
    }
})

function nthOccurrence(str, c, n) {
    var pos = str.indexOf(c, 0);
    while (n-- > 0 && pos != - 1)
        pos = str.indexOf(c, pos + 1);
    return pos;
}

function toDateTime(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = parseMonth(date.getMonth());
    var year = date.getFullYear();
    var hours = date.getHours();
    var ampm = "AM";
    if (hours > 12) {
        hours -= 12;
        ampm = "PM";
    }
    hours = String("0" + hours).slice(-2);
    var minutes = String("0" + date.getMinutes()).slice(-2);
    return month + ' ' + day + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
}

function getDatenTime(date) {
    var day = String("0" + date.getDate()).slice(-2);
    var month = parseMonth(date.getMonth());
    var year = date.getFullYear();
    var hours = date.getHours();
    var ampm = "AM";
    if (hours > 12) {
        hours -= 12;
        ampm = "PM";
    }
    hours = String("0" + hours).slice(-2);
    var minutes = String("0" + date.getMinutes()).slice(-2);
    return [month + ' ' + day + ' ' + year, hours + ':' + minutes + ' ' + ampm];
}

function parseMonth(month) {
    switch (month) {
        case 0:
            return "Jan";
        case 1:
            return "Feb";
        case 2:
            return "Mar";
        case 3:
            return "Apr";
        case 4:
            return "May";
        case 5:
            return "Jun";
        case 6:
            return "Jul";
        case 7:
            return "Aug";
        case 8:
            return "Sep";
        case 9:
            return "Oct";
        case 10:
            return "Nov";
        case 11:
            return "Sep";

    }
}
